<!doctype html>
<html lang="en">

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Template • TodoMVC</title>
	<link rel="stylesheet" href="node_modules/todomvc-common/base.css">
	<link rel="stylesheet" href="node_modules/todomvc-app-css/index.css">
	<!-- CSS overrides - remove if you don't need it -->
	<link rel="stylesheet" href="css/app.css">
</head>

<body>
	<div id="root-react"></div>

	<!-- Scripts here. Don't remove ↓ -->
	<script src="node_modules/react/umd/react.development.js"></script>
	<script src="node_modules/react-dom/umd/react-dom.development.js"></script>
	<script src="node_modules/babel-standalone/babel.min.js"></script>
	<script src="node_modules/todomvc-common/base.js"></script>
	<!-- <script src="js/app.js"></script> -->
	<script type="text/babel">
		//定义数组
		const todosList = [
			{
				id: 1,
				name: 'V1.0 原生实现',
				checkstate: false
			},
			{
				id: 2,
				name: 'V2.0 Vue实现',
				checkstate: false
			},
			{
				id: 3,
				name: 'V3.0  React实现',
				checkstate: true
			}
		];

		class RootComponent extends React.Component {
				constructor(props) {
					super(props);
					this.state = {
						todosList:todosList,  //列数据
						showType:"all",   //展示类型（all：全部，active：进行中，Completed：完成）
						clearState:false,
					}
					this.myRef = React.createRef()
				}


			componentWillMount() {
			}
			componentDidMount() {
				//组件挂载时候，注册keypress事件
				document.addEventListener('keypress',this.handleEnterKey)
			}
			componentWillUnmount() {
				//组件卸载时候，注销keypress事件
  				document.removeEventListener("keypress",this.handleEenterKey)
			}
			
			
			
			/**
			 * 点击全选
			 * @param paramId 列数据id
			*/
			handleSelectAll = (paramId) =>{
				let { todosList } = this.state;  //全部列数据
				let isSelectAll=false;  //是否存在未选中数据
				let newData=[];    //格式化后新的列数据
				for(let i=0;i<todosList.length;i++){
					if (!todosList[i].checkstate) {
						isSelectAll=true;
						break;
					}
				}
				if(isSelectAll){  //存在没有选择中的列
					newData=todosList.map((item,index)=>{
						return ({ id: item.id, name: item.name, checkstate: true });
					})
				}else{
					newData=todosList.map((item,index)=>{
						return ({ id: item.id, name: item.name, checkstate: false });
					})
				}
				this.setState({
					todosList:newData
				},()=>{
					//console.log(this.state.todosList,"全选");
				});
			}
			

			/**
			 * 点击选中
			 * @param paramId 列数据id
			*/
			handleCheckClick = (paramId) =>{
				let { todosList } = this.state;
				let newData=todosList.map((item,index)=>{
					if (parseInt(item.id,10) === parseInt(paramId,10)) {
						item.checkstate=!item.checkstate;
					}
					return item;
				})
				this.setState({
					todosList:newData
				},()=>{
					//console.log(this.state.todosList,"选中");
				});
			}
			

			/**
			 * 点击监听checkbox状态（checked与defaultChecked只能任选一个，defaultChecked：只检测初始状态的checked）
			 * 这里暂时只用作处理dom控制台报错问题，声明以下即可
			 * @param e 
			*/
			handleCheckboxChange = (e) =>{
			}
			
			

			/**
			 * 双击编辑文本
			*/
			handleLabelDoubleClick=(e)=>{
				var focusCount = document.querySelectorAll(".editing").length;
				if(focusCount > 0){
					return;
				}
				if (e.currentTarget.className.indexOf("editing")<0) {
					e.currentTarget.className=e.currentTarget.className+" editing";
					e.target.parentElement.parentElement.querySelector(".edit").focus();
				}
			}

			/**
			* 失去焦点保存
			*/
			handleBlur =(paramId,e)=> {
				if((e.target.value).replace(/ /g,'') === ""){
					//var r=window.confirm("当前输入填入内容不能为空!");
					//if (r==true){}else{} 
					e.target.style.border="1px solid red"
					return e.target.focus();
				}
				e.target.style.border="1px solid #999"
				if (e.target.parentNode.className.indexOf("editing")>0) {
					e.target.parentNode.className=e.target.parentNode.className.replace("editing","");
				}
				const {todosList} = this.state;
				let newData=todosList.map((item,index)=>{
					if (parseInt(item.id,10) === parseInt(paramId,10)) {
						item.name=e.target.value;
					}
					return item;
				})
				this.setState({
					todosList:newData
				},()=>{
					//console.log(this.state.todosList,"保存");
				});
			}


			/**
			 * 点击清除当前数据
			 * @param paramId 列数据id
			*/
			handleRemoveItem =(paramId)=>{
				let { todosList } = this.state;
				let newTodosList = todosList.filter(todo => todo.id !== paramId)
				this.setState({
					todosList:newTodosList
				},()=>{
					//console.log(this.state.todosList,"删除");
				});
			}

			/**
			 * 点击展示所有数据
			 * @param paramId 列数据id
			*/
			handleShowAll =(e)=> {
				let array = e.target.parentNode.offsetParent.childNodes;
				for (let index = 0; index < array.length; index++) {
					e.target.parentNode.offsetParent.childNodes[index].childNodes[0].className="";
				}
				e.target.className="selected";
				this.setState({
					showType:"all"
				})
			}

			/**
			 * 点击只展示进行中数据
			 * @param paramId 列数据id
			*/
			handleShowActive =(e)=> {
				let array = e.target.parentNode.offsetParent.childNodes;
				for (let index = 0; index < array.length; index++) {
					e.target.parentNode.offsetParent.childNodes[index].childNodes[0].className="";
				}
				e.target.className="selected";
				this.setState({
					showType:"active"
				})
			}

			/**
			 * 点击只展示完成的数据
			 * @param paramId 列数据id
			*/
			handleShowCompleted =(e)=> {
				let array = e.target.parentNode.offsetParent.childNodes;
				for (let index = 0; index < array.length; index++) {
					e.target.parentNode.offsetParent.childNodes[index].childNodes[0].className="";
				}
				e.target.className="selected";
				this.setState({
					showType:"Completed"
				})
			}


			/**
			 * 点击清除全部完成的数据
			*/
			handleRemoveAll =()=>{
				let newObj=[];
				let array = this.state.todosList;
				for (let item in array) {
					console.log(array[item])
					if (!array[item].checkstate) {
						newObj.push(array[item])
					}
				}
				this.setState({
					todosList:newObj
				})
			}
			
			/**
			 * 绑定键盘回车事件
			*/
			hanldeAddItem = (e) => {
				if(e.charCode === 13){ //主要区别就是这里，可以直接获取到keyCode的值
					if(e.target.value.replace(/ /g,'')==="") return alert("不能添加空内容！");
					const newTodosList=this.state.todosList;
					let value = e.target.value;
					if(!value) return false;
					let newTodoItem = {
						id: +new Date(),
						name: value,
						checkstate: false
					};
					e.target.value = '';
					newTodosList.push(newTodoItem)
					this.setState({
						todosList: newTodosList
					},()=>{
						//console.log(this.state.todosList,"添加");
					});
				}
			}

			
			render() {
				const { todosList } = this.state;

				let todosListElement=todosList.map((item,index)=>{
					let showElement = "";
					switch (this.state.showType) {
						case "active":  //进行中
							if (!item.checkstate) {
								showElement = 
								<li className={item.checkstate?"completed":""} key={item.id}  onDoubleClick={this.handleLabelDoubleClick}>
									<div className="view" >
										<input onClick={this.handleCheckClick.bind(this,item.id)} className="toggle" type="checkbox" checked={item.checkstate} onChange={this.handleCheckboxChange} />
										<label >{item.name}</label>
										<button onClick={this.handleRemoveItem.bind(this,item.id)} className="destroy"></button>
									</div>
									<input className="edit" defaultValue={item.name}
										onBlur={ this.handleBlur.bind(this,item.id) }
										 placeholder="该内容不能为空"
									/>
								</li>
							}
							break;
						case "Completed":  //完成
							if (item.checkstate) {
								showElement = 
								<li className={item.checkstate?"completed":""} key={item.id}  onDoubleClick={this.handleLabelDoubleClick}>
									<div className="view" >
										<input onClick={this.handleCheckClick.bind(this,item.id)} className="toggle" type="checkbox" checked={item.checkstate} onChange={this.handleCheckboxChange} />
										<label >{item.name}</label>
										<button onClick={this.handleRemoveItem.bind(this,item.id)} className="destroy"></button>
									</div>
									<input className="edit" defaultValue={item.name}
										onBlur={ this.handleBlur.bind(this,item.id) }
										 placeholder="该内容不能为空"
									/>
								</li>
							}
							break;
					
						default:
							showElement = 
								<li className={item.checkstate?"completed":""} key={item.id}  onDoubleClick={this.handleLabelDoubleClick}>
									<div className="view" >
										<input onClick={this.handleCheckClick.bind(this,item.id)} className="toggle" type="checkbox" checked={item.checkstate} onChange={this.handleCheckboxChange} />
										<label >{item.name}</label>
										<button onClick={this.handleRemoveItem.bind(this,item.id)} className="destroy"></button>
									</div>
									<input className="edit" defaultValue={item.name}
										onBlur={ this.handleBlur.bind(this,item.id) }
										 placeholder="该内容不能为空"
									/>
								</li>
							break;
					}
					return showElement;
				})

				return (
					<div>
						<div className="todoapp">
							<div className="div">
								<h1>todos</h1>
								<input className="new-todo" placeholder="What needs to be done?" ref={this.myRef} onKeyPress={this.hanldeAddItem} />
							</div>
							{
								todosList.length>0?
								<React.Fragment>
									<div className="main">
										<input id="toggle-all" className="toggle-all" type="checkbox" />
										<label htmlFor="toggle-all" onClick={this.handleSelectAll}>Mark all as complete</label>
										<ul className="todo-list">
											{todosListElement}
										</ul>
									</div>
									<footer className="footer">
										<span className="todo-count"><strong>{(todosList.filter(function (item) { return item.checkstate })).length}</strong> item left</span>
										<ul className="filters">
											<li>
												<a className="selected" href="#/" onClick={this.handleShowAll}>All</a>
											</li>
											<li>
												<a href="#/active"  onClick={this.handleShowActive}>Active</a>
											</li>
											<li>
												<a href="#/completed" onClick={this.handleShowCompleted}>Completed</a>
											</li>
										</ul>
										{
											(todosList.filter(function (item) { return item.checkstate })).length > 0?
											<button className="clear-completed" onClick={this.handleRemoveAll}>Clear completed</button>
											:""
										}
									</footer>
								</React.Fragment>:""
							}
							
							
						</div>
						<footer className="info">
							<p>Double-click to edit a todo</p>
							<p>Template by <a href="http://sindresorhus.com">Sindre Sorhus</a></p>
							<p>Created by <a href="http://todomvc.com">you</a></p>
							<p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
						</footer>
					</div>
				);
			}
		}
		ReactDOM.render(
			<div>
				<RootComponent />
			</div>,
			document.getElementById('root-react')
		);
	</script>
</body>

</html>
